package payment.api;

import java.io.IOException;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import payment.Pays;
import payment.api.Pay.PayMethod;

public class PayResult implements HttpHandler {
    /**
     * GET: token: String
     * return: {@code Pays.Status}, SUCCESS: 200, CANCEL: 400, TIMEOUT: 500, null:
     * 404
     */
    @Override
    public void handle(HttpExchange exchange) throws IOException {
        var args = exchange.getRequestURI().toString().replace("/payResult?token=", "").replace("method=", "")
                .split("&");
        Pays.Status status = null;
        if (args[1].equals("WX"))
            status = Pays.pay(args[0], PayMethod.WX);
        else
            status = Pays.pay(args[0], PayMethod.ZFB);
        exchange.sendResponseHeaders(200, 0);
        String html = new String(PayResult.class.getResourceAsStream("payResult.html").readAllBytes());
        if (status == null) {
            html = String.format(html, args[0], "null");
        } else {
            html = String.format(html, args[0], status.toString());
        }
        exchange.getResponseBody().write(html.getBytes());
        exchange.close();
    }
}
